﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace SkypengerApp.Data
{
    public static class DataHelper
    {

        /// <summary>
        /// Loads this instance.
        /// </summary>
        /// <returns></returns>
        public static Diary Load()
        {
            Diary diary = new Diary();
            string filePath = "Data/Contacts.xml";

            try
            {
                XmlSerializer xs = new XmlSerializer(typeof(Diary));
                using (StreamReader sr = new StreamReader(filePath))
                {
                    diary = xs.Deserialize(sr) as Diary;
                }
            }
            catch (Exception)
            {
                //TODO log
            }

            return diary;
        }

        /// <summary>
        /// Adds the contact.
        /// </summary>
        /// <param name="diary">The diary.</param>
        /// <param name="name">The name.</param>
        /// <param name="ip">The ip.</param>
        /// <param name="port">The port.</param>
        /// <returns></returns>
        public static bool AddContact(this Diary diary, string name, string ip, int port)
        {
            bool added = true;
            string filePath = "Data/Contacts.xml";

            try
            {
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(Diary));
                Contact contact = new Contact()
                {
                    Name = name,
                    IP = ip,
                    Port = port
                };

                diary.Contacts.Add(contact);

                using (StreamWriter sw = new StreamWriter(filePath))
                {
                    xmlSerializer.Serialize(sw, diary);
                }
            }
            catch (Exception)
            {
                //TODO log
                added = false;
            }

            return added;
        }
    }
}
